package com.sky.controller.user;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sky.constant.IsDefaultConstant;
import com.sky.entity.AddressBook;
import com.sky.result.Result;
import com.sky.service.IAddressBookService;
import com.sky.utils.ThreadLocalUtil;
import org.apache.ibatis.io.ResolverUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user/addressBook")
public class AddressBookController {
    @Autowired
    private IAddressBookService iAddressBookService;

    @GetMapping("/default")
    public Result isDefault(){
        LambdaQueryWrapper<AddressBook >lqw =new LambdaQueryWrapper<>();
        lqw.eq(AddressBook::getIsDefault, IsDefaultConstant.YES);
        lqw.eq(AddressBook::getUserId, ThreadLocalUtil.getValue());
        AddressBook one = iAddressBookService.getOne(lqw);
        return Result.success(one);
    }

    @GetMapping("/list")
    public Result list (){
        LambdaQueryWrapper<AddressBook >lqw =new LambdaQueryWrapper<>();
        lqw.eq(AddressBook::getUserId, ThreadLocalUtil.getValue());
        List<AddressBook> list = iAddressBookService.list(lqw);
        return Result.success(list);
    }

    @PutMapping("/default")
    public Result updateDefault(@RequestBody AddressBook addressBook){
        //需要事务
        iAddressBookService.updateDefault(addressBook);
        return Result.success();
    }

    @PostMapping
    public Result add (@RequestBody AddressBook addressBook){
        addressBook.setUserId((Long) ThreadLocalUtil.getValue());
        iAddressBookService.save(addressBook);
        return Result.success();
    }

    @GetMapping("/{addressId}")
    public Result getOne (@PathVariable Long addressId){
        AddressBook byId = iAddressBookService.getById(addressId);
        return Result.success(byId);
    }

    @PutMapping
    public Result update(@RequestBody AddressBook addressBook){
        iAddressBookService.updateById(addressBook);
        return Result.success();
    }

    @DeleteMapping
    public Result delete(Long id){
        iAddressBookService.removeById(id);
        return Result.success();
    }


}
